import React, {PureComponent} from 'react';
import {connect} from 'dva';

import {Button, Card, DatePicker, Form, Icon, Input, Modal, Radio, Select, Tooltip, Upload,} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './style.less';
import UEditor from '../../ueditor/UMEditor';
import NEditor from "../../components/NEditor/NEditor";

const FormItem = Form.Item;
const {Option} = Select;

const {TextArea} = Input;

@connect(state => ({
    service: state.service,
}))
@Form.create()
export default class ServiceAdd extends PureComponent {
    state = {
        thumbUrl: '',
        previewVisible: false,
        previewImage: '',
        fileList: [],
    }

    componentDidMount() {
        this.props.dispatch({
            type: 'service/fetchCategories',
        });
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                this.props.dispatch({
                    type: 'service/add',
                    payload: values,
                    callback: () => {
                        this.props.form.resetFields();
                    },
                });
            }
        });
    }

    handleCancel = () => this.setState({ previewVisible: false })

    handlePreview = (file) => {
        console.log(file);
        this.setState({
            previewImage: file.response.data.url,
            previewVisible: true,
        });
    }

    thumbUpload = (info) => {
        if (info.file.status === 'done') {
            const thumbUrl = info.file.response.data.url;
            this.setState({
                thumbUrl,
            });
            return info.file.response.data.file;
        }
    }
    photosChange = (info) => {
        if (info.file.status === 'done') {
            this.state.fileList.push(info.file.response.data.file);
            this.setState({
                fileList: this.state.fileList,
            });
            return this.state.fileList;
        }
    }
    beforeUpload = () => {

    }

    render() {
        const {service: {categories, loading}} = this.props;
        const {getFieldDecorator} = this.props.form;
        const thumbUrl = this.state.thumbUrl;
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
          <div>
            <Icon type="plus" />
            <div className="ant-upload-text">上传图片</div>
          </div>
        );
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 17},
                md: {span: 14},
            },
        };
        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };
        return (
          <PageHeaderLayout title="新增服务" content="新增零工服务，下列的所有内容均需填写">
            <Card bordered={false}>
              <Form
                onSubmit={this.handleSubmit}
                hideRequiredMark
                style={{marginTop: 8}}
              >
                <FormItem
                  {...formItemLayout}
                  label="服务名称"
                >
                  {getFieldDecorator('name', {
                                rules: [{
                                    required: true, message: '请输入服务名称',
                                }],
                            })(
                              <Input placeholder="服务名称" />
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={
                    <span>
                  服务类别
                  <em className={styles.optional}>
                      &nbsp;
                    <Tooltip title="选择需要添加到的类别">
                      <Icon type="info-circle-o" style={{marginRight: 4}} />
                    </Tooltip>
                  </em>
                    </span>
                      }
                >
                  {getFieldDecorator('pid', {initialValue: 0})(
                    <Select>
                      <Option value={0}>顶级分类</Option>
                      {categories.map((item, i) => (
                        <Option key={`${item.id}-${i}-category`} value={item.id}>{item.name}</Option>
                              ))}
                    </Select>
                      )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="服务简介"
                >
                  {getFieldDecorator('description', {
                                rules: [{
                                    required: true, message: '请输入目标描述',
                                }],
                            })(
                              <TextArea style={{minHeight: 32}} placeholder="请输入服务简介" rows={4} />
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="预估金额"
                  hasFeedback
                >
                  {getFieldDecorator('price', {
                                rules: [{
                                    required: true,
                                    message: '请输入正确的预估金额',
                                    pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                                }],
                            })(
                              <Input placeholder="预估金额" />
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={
                    <span>
                    预估价格单位
                    <em className={styles.optional}>
                        &nbsp;
                      <Tooltip title="单位是当前分类的计价单位如：平方米">
                        <Icon type="info-circle-o" style={{marginRight: 4}} />
                      </Tooltip>
                    </em>
                    </span>
                            }
                  hasFeedback
                >
                  {getFieldDecorator('unit', {
                                rules: [{
                                    required: true,
                                    message: '请输入预估价格单位',
                                }],
                                initialValue: '㎡',
                            })(
                              <Input width={{width: '50%'}} placeholder="预估价格单位" />
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="缩略图"
                >
                  <div className="dropbox">
                    {getFieldDecorator('thumb', {
                              valuePropName: 'thumb',
                              getValueFromEvent: this.thumbUpload,
                        rules: [{
                            required: true,
                            message: '请上传缩略图',
                        }],
                          })(
                            <Upload.Dragger showUploadList={false} name="file" action={`/api/upload?token=${sessionStorage.getItem('access_token')}`}>
                              {thumbUrl ? <img src={thumbUrl} alt="" className={styles.thumb} /> :
                              <div>
                                <p className="ant-upload-drag-icon">
                                  <Icon type="inbox" />
                                </p>
                                <p className="ant-upload-text">点击或拖拽上传</p>
                              </div>}
                            </Upload.Dragger>
                          )}
                  </div>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="相册"
                >
                  <div className="dropbox">
                    {getFieldDecorator('photos', {
                              valuePropName: 'photos',
                              getValueFromEvent: this.photosChange,
                              rules: [{
                                  required: true,
                                  type: 'array',
                                  max: 5,
                                  min: 1,
                                  message: '请上传相册',
                              }],
                          })(
                            <Upload onPreview={this.handlePreview} listType="picture-card" name="file" action={`/api/upload?token=${sessionStorage.getItem('access_token')}`}>
                              {fileList.length >= 5 ? null : uploadButton}
                            </Upload>
                          )}
                  </div>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="首页显示"
                >
                  {getFieldDecorator('show_index', {initialValue: 0})(
                    <Radio.Group>
                      <Radio value={0}>否</Radio>
                      <Radio value={1}>是</Radio>
                    </Radio.Group>
                      )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="状态"
                >
                  {getFieldDecorator('status', {initialValue: 1})(
                    <Radio.Group>
                      <Radio value={0}>禁用</Radio>
                      <Radio value={1}>启用</Radio>
                    </Radio.Group>
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="内容详情"
                >
                  {getFieldDecorator('content', {
                                initialValue: '',
                                rules: [{
                                    required: true,
                                    message: '请输入详情内容',
                                }],
                            })(
                              <NEditor />
                            )}
                </FormItem>
                <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                  <Button type="primary" htmlType="submit" loading={loading}>
                                提交
                  </Button>
                  <Button onClick={() => { this.props.form.resetFields(); }} style={{marginLeft: 8}}>重置</Button>
                </FormItem>
              </Form>
            </Card>
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="图片预览" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </PageHeaderLayout>
        );
    }
}
